<?php
namespace App\Http\Middleware;
use App\Exceptions\InternalException;
use App\Exceptions\InvalidTokenException;
use App\Exceptions\TokenInvalidException;
use App\Services\TokenService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

/**
 * @Author: dxf
 * @Date: 2021-07-19
 * @Time: 14:28
 */

/**
 *
 */
class TokenMiddleware{

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws InternalException
     * @throws TokenInvalidException
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        $client = $request->header('client');

        if($token){
            $tokenService = new TokenService();
            //拿到token
            //拆分成3段
            //验签
            //延长token有效期
            //返回个人信息和权限
            $expire_time  = $client == 'admin' ? config('token.admin_expire_time', 604800) : config('token.app_expire_time', 604800);
            $check_arr = explode('.', base64_decode($token,true));
            $check_hs256 = $tokenService->hmacSha256($check_arr[2]);
            if ($tokenService->checkTokenArr($check_arr)) {

                $user_info = Redis::get($check_hs256);
                if (!$user_info) {
                    //app或者小程序 过期的时候需要去再次请求登录的接口
                    throw new TokenInvalidException('Token已经过期或无效Token');
                } else {
                    $tokenService->refreshToken($check_arr[0],$check_hs256, $expire_time);
                }
//                $user_info = json_decode($user_info, true);
                $user_info = unserialize($user_info);
//                $user_token = $check_arr[1];
                $request->attributes->add(compact('user_info'));
//                $request->attributes->add(compact('user_token'));
            }
        }else{
            throw new TokenInvalidException('无效Token');
        }

        return $next($request);
    }

}
